/**
wifi按键
2018.06.08

*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Time.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#include <TimeAlarms.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>

// Hardware SPI (faster, but must use certain hardware pins):
// pin14 D5 SCK is LCD serial clock (SCLK) - this is pin 14 on Huzzah ESP8266
// pin13 D7 - Data/Command select (D/C) on an Huzzah ESP8266
// pin12 D6 MOSI is LCD DIN - this is pin 13 on an Huzzah ESP8266
// pin5 D1 - LCD chip select (CS)
// pin4 D2 - LCD reset (RST)
Adafruit_PCD8544 display = Adafruit_PCD8544(12, 5, 4); //LCD实例
WiFiClient client; //wifi实例
HTTPClient httpClient; //http通信实例
String httpString;
String sn_id="30101"; //本机ID号第一位为预留表示楼层，2.3位为产线  3.4位为工位
String sn_ver="0.10"; //系统版本号
const char* ssid ="Oklahoma";        // XXXXXX -- 使用时请修改为当前你的 wifi ssid
const char* password ="pl67847288";         // XXXXXX -- 使用时请修改为当前你的 wifi 密码

unsigned char str_tmp[3][40][33] = {0}; //汉字缓存 3行 每行40个字

String API_host = "http://192.168.43.241:8080"; //服务器地址

const unsigned long BAUD_RATE = 115200;                   // 串口调试速度
const unsigned long HTTP_TIMEOUT = 300;                  // HTTP延时等待
const size_t MAX_CONTENT_SIZE = 2048;                    // HTTP 接收最大？？？有BUG最多只能530 并不能达到2048待查明
char key_sel=0;
char wait_come=0;
//static const unsigned char PROGMEM str_1[] = {64, 2, 39, 194, 36, 66, 132, 82, 69, 82, 85, 82, 21, 82, 37, 82, 37, 82, 37, 82, 197, 82, 65, 2, 66, 130, 66, 66, 68, 74, 72, 4 };  //中文字符调试用


//  -- 跳过 HTTP 头，使我们在响应正文的开头
bool skipResponseHeaders() {
  // HTTP headers end with an empty line
  char endOfHeaders[] = "\r\n\r\n";

  client.setTimeout(HTTP_TIMEOUT);
  bool ok = client.find(endOfHeaders);

  if (!ok) {
    Serial.println("No response or invalid response!");
  }

  return ok;
}


// 发送请求指令
bool sendRequest(const char* host, String GetUrl) {
  if (GetUrl == "")
  {
    String GetUrl = "test";
  }
  // This will send the request to the server
  client.print(String("GET ") + "/" + GetUrl + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  return true;
}

// Read the body of the response from the HTTP server -- 从HTTP服务器响应中读取正文
void readReponseContent(char* content, size_t maxSize) {
  size_t length = client.peekBytes(content, maxSize);
  delay(100);
  Serial.println(length);
  Serial.println("Get the data from Internet!");
  content[length] = 0;
  Serial.println("Read Over!");
}

bool lcd3Display(unsigned char zi[3][40][33], char fresh, char sspeed)
{
  display.clearDisplay();
  display.setTextSize(2);             //设置字体大小
  char row_num = 1; //从数组一开始为字
  char zi_num = 0;
  char page = fresh / sspeed;
  char sel=0;
  
  for (char row = 0; row < 3; row++)
  {
    row_num = 1;
    if (((fresh&B00000001))&&(row==0))
  {
 sel=1;
  }
  else
  if(((fresh&B00000010))&&(row==1))
    {
  sel=1;
    }
    else
    if(((fresh&B00000100))&&(row==2))
    {
 sel=1;
     }
    else
    {
 sel=0;
      }  

    while (zi[row][row_num][0] != 0)
    {
      if (zi[row][row_num][0] == 1) //汉字为1
      {
            if(sel==1)
            {
            display.drawBitmap(16 * (row_num - 1), 16 * row, &zi[row][row_num][1], 16, 16, 0,1); //显示汉字
             }
            else
            {
              display.drawBitmap(16 * (row_num - 1), 16 * row, &zi[row][row_num][1], 16, 16, 1,0); //显示汉字
              }
      }
      else if (zi[row][row_num][0] == 2) //ascii为2
      {

       if(sel==1)
      {
      display.setTextColor(WHITE, BLACK); //设置字体黑色，字体背景白色 
       }
      else
      {
        display.setTextColor(BLACK, WHITE); //设置字体黑色，字体背景白色 
        }
          
        display.setCursor(16 * (row_num - 1) + 3, 16 * row);    //设置字体的起始位置
        display.printf("%c", zi[row][row_num][1]);
      }
      row_num++;
    }

  }
  display.display();
}


// Close the connection with the HTTP server -- 关闭与HTTP服务器连接
void stopConnect() {
  Serial.println("Disconnect");
  client.stop();
}

void readLcdInfo(String  rep,char line )  //LCD读取到缓存
{
    int commaPosition;
    int lastPosition;
    commaPosition = rep.indexOf('[');  //去掉第一个[
    rep = rep.substring(commaPosition + 1, rep.length());  //去掉第一个[
    int zishu=0;
    int zibit=0;
    do {
      commaPosition = rep.indexOf('['); //第一个[
      if(commaPosition==0)
         { 
           zibit=0;
           zishu++;
           zishu=zishu;
           commaPosition = rep.indexOf(',');
            Serial.println("类型为:");
           Serial.println(rep.substring(1, commaPosition));
           str_tmp[line][zishu][zibit]=(unsigned char)(rep.substring(1, commaPosition).toInt());
           zibit++;
           rep = rep.substring(commaPosition + 1, rep.length());
          }
          
      commaPosition = rep.indexOf(',');
      if (commaPosition != -1)
      {
         lastPosition= rep.indexOf(']');
            if(lastPosition==commaPosition-1)
              {
                Serial.println(rep.substring(0, lastPosition));
                str_tmp[line][zishu][zibit]=(unsigned char)(rep.substring(0, lastPosition).toInt());
                zibit++;
                rep = rep.substring(commaPosition + 1, rep.length());
                
               }
         else
         {
        Serial.println(rep.substring(0, commaPosition));
        str_tmp[line][zishu][zibit]=(unsigned char)(rep.substring(0, commaPosition).toInt());
        zibit++;
        rep = rep.substring(commaPosition + 1, rep.length());
         }
      }
      else {
        if (rep.length() > 0) {
          Serial.println(rep.substring(0, rep.length()-4));
          str_tmp[line][zishu][zibit]=(unsigned char)(rep.substring(0, rep.length()-4).toInt());
          zibit++;
        }
      }
    }
    while (commaPosition >= 0);

    }


unsigned char send_cmd(String cmd,char papr)   //命令发送与接收处理
{
  String send_cmd;
  char response[MAX_CONTENT_SIZE];
  String rep;
 if(cmd=="inint")
{
  if(papr==0)
  {
  send_cmd=String("/")+cmd+"_"+sn_id+"_0";
  }
  else 
 if(papr==1)
 {
  send_cmd=String("/")+cmd+"_"+sn_id+"_1";
  }
  else 
 if(papr==2)
 {
  send_cmd=String("/")+cmd+"_"+sn_id+"_2";
  }
  Serial.println(send_cmd);
  
  httpClient.begin(API_host+send_cmd);
  int httpCode = httpClient.GET();
    if (httpCode > 0) 
    {
    if (httpCode == HTTP_CODE_OK) 
    {
        httpString = httpClient.getString();
        Serial.println("xz_info:");
        Serial.println(httpString);
        readLcdInfo(httpString,papr); //发送到LCD缓存 
    }
    }
    return 1;
  }
  
 if(cmd=="keysend")
{
  String S1,S2,S3;
    S1="_key1";
    S2="_key2";
    S3="_key3";
    send_cmd=String("/")+sn_id+"_"+cmd;
    if(((papr&B00000001)))  { send_cmd=send_cmd+S1;}
    if(((papr&B00000010)))  { send_cmd=send_cmd+S2;}
    if(((papr&B00000100)))  { send_cmd=send_cmd+S3;}
    
  httpClient.begin(API_host+send_cmd);
  int httpCode = httpClient.GET();
    if (httpCode > 0) 
    {
    if (httpCode == HTTP_CODE_OK) 
    {
        httpString = httpClient.getString();
        Serial.println("xz_info:");
        Serial.println(httpString);
    }
    }
    return 1;
  }
   if(cmd=="come")
{
    
  send_cmd=String("/")+sn_id+"_"+cmd;
  
  httpClient.begin(API_host+send_cmd);
  int httpCode = httpClient.GET();
    if (httpCode > 0) 
    {
    if (httpCode == HTTP_CODE_OK) 
    {
        httpString = httpClient.getString();
        Serial.println("xz_info:");
        Serial.println(httpString);
        if(httpString.indexOf("isok")!=-1)
      {
        return 1;
      }else
      {
        return 0;
       } 
    }
    }
  }
  client.stop(); 
}
void setup() {
  // Initialize LCD
  display.begin();
  display.setContrast(50);
  display.setTextSize(1);
  display.setTextColor(BLACK);
  //display.setTextColor(WHITE, BLACK); //设置字体黑色，字体背景白色   
  display.clearDisplay();
  display.print("ver:");
  display.println(sn_ver);
  display.print("Connecting...");
  display.display();
  
  WiFi.mode(WIFI_STA);     //设置esp8266 工作模式
  Serial.begin(BAUD_RATE );      //设置波特率
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  
  pinMode(16, INPUT);//按键初始化
  pinMode(15, INPUT);
  pinMode(0, INPUT);
  pinMode(2, INPUT);
  WiFi.begin(ssid, password);   //连接wifi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  send_cmd("inint",0);
  delay(300);
  send_cmd("inint",1);
  delay(300);
  send_cmd("inint",2);
  delay(300);
  
  lcd3Display(str_tmp,0x00, 10); //屏幕刷新
  delay(5000);
}




void loop() {
  char response[MAX_CONTENT_SIZE];
  if(wait_come==0) //正常情况
  {
    if (digitalRead(0) == 0)
  {
    delay(100);
    if (digitalRead(0) == 0)
    {
     key_sel=key_sel^B00000001;
     lcd3Display(str_tmp,key_sel, 10);
    }

  }
  if (digitalRead(16) == 0)
  {
    delay(100);
    if (digitalRead(16) == 0)
    {
    key_sel=key_sel^B00000010;
     lcd3Display(str_tmp,key_sel, 10);
    }

  }
  if (digitalRead(15) == 1)
  {
    delay(100);
    if (digitalRead(15) == 1)
    {
      key_sel=key_sel^B00000100;
     lcd3Display(str_tmp,key_sel, 10);
      }
    }


   if (digitalRead(2) == 0)
  {
    delay(100);
    if (digitalRead(2) == 0)
    {
      if(key_sel!=0)
      {
      wait_come=1;
      Serial.println("key");
      send_cmd("keysend",key_sel);
      display.clearDisplay();
      display.setTextSize(2);             //设置字体大小
      display.print("wait...");
      display.display();
      }
    }
  }

  }else
  {
 
   if (digitalRead(2) == 0)
  {
    delay(100);
    if (digitalRead(2) == 0)
    {
      char bk=0;
      bk=send_cmd("come",1);
      if(bk==1)
      {
      wait_come=0;
      key_sel=0;
      lcd3Display(str_tmp,key_sel, 10); 
      }     
    }
  }   
    
    }

  
}
